package app

import (
	"gin-wheel/global"
	"gin-wheel/pkg/util"
	"time"

	"github.com/dgrijalva/jwt-go"
)

// 打包userid等到token中
type Claims struct {
	Userid   string `json:"userid"`
	Username string `json:"username"`
	Phone    string `json:"phone"`
	jwt.StandardClaims
}

func GetJWTSecret() []byte {
	return []byte(global.JWTSetting.Secret)
}

// 注册用户id 用户名等信息到token中
func GenerateToken(userid int, username, phone string, expireSeconds int64) (string, error) {
	hashUseridParam := [1]int{userid}
	claims := Claims{
		Userid:   util.EnHashids(hashUseridParam[:]),
		Username: username,
		Phone:    phone,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + expireSeconds,
		},
	}

	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString(GetJWTSecret())
	return token, err
}

// 解析token
func ParseToken(token string) (*Claims, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return GetJWTSecret(), nil
	})
	if err != nil {
		return nil, err
	}
	if tokenClaims != nil {
		claims, ok := tokenClaims.Claims.(*Claims)
		if ok && tokenClaims.Valid {
			return claims, nil
		}
	}

	return nil, err
}
